package com.lijinjiang.view;

import com.lijinjiang.exception.QueryException;
import com.lijinjiang.model.QueryData;
import com.lijinjiang.model.table.DataCell;
import com.lijinjiang.model.table.DataColumn;
import com.lijinjiang.model.tree.Database;
import com.lijinjiang.model.tree.Table;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @ClassName DataTable
 * @Description 表单数据页面
 * @Author Li
 * @Date 2022/8/21 23:11
 * @ModifyDate 2022/8/21 23:11
 * @Version 1.0
 */
public class DataTable extends JScrollPane {
    private Database db; // 数据库

    private String sql; // SQL 语句

    public DataTable(Database db, String sql) throws QueryException {
        super();
        this.db = db;
        this.sql = sql;
        initDataTable(); // 初始化数据区域
        this.setBorder(null);
        this.setViewportBorder(null);
    }

    // 初始化
    private void initDataTable() throws QueryException {
        QueryData queryData = new QueryData(db, sql);
        ResultSet rs = queryData.getData();
        if (rs != null) {
            try {
                // 获取数据的全部列名作为表头
                List<DataColumn> columns = new ArrayList<>();
                ResultSetMetaData metaData = rs.getMetaData();
                int count = metaData.getColumnCount();
                for (int i = 1; i <= count; i++) {
                    // getColumnLabel:获取建议标题，有 AS获取 AS后面的，没有则获取 getColumnName
                    String name = metaData.getColumnLabel(i);
                    columns.add(new DataColumn(i, name));
                }
                // 获取全部数据
                int columnCount = columns.size();
                List<DataCell[]> dataCells = new ArrayList<>();
                int i = 0;
                while (rs.next()) {
                    DataCell[] data = new DataCell[columnCount];
                    //遍历列, 创建每一个单元格对象
                    for (int j = 0; j < columnCount; j++) {
                        //得到具体的某一列
                        DataColumn column = columns.get(j);
                        //创建单元格对象
                        DataCell dc = new DataCell(i, column, rs.getString(column.getName()));
                        data[j] = dc;
                    }
                    dataCells.add(data);
                }

                // 构造 JTable 模型，初始化数据
                DefaultTableModel tableModel = new DefaultTableModel(dataCells.toArray(new DataCell[0][0]), columns.toArray());
                JTable dataTable = new JTable(tableModel);
                JTableHeader tableHeader = dataTable.getTableHeader();
                tableHeader.setBorder(null);
                tableHeader.setFont(new Font("微软雅黑", Font.BOLD, 14));
                dataTable.setRowHeight(28);
                dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                fitTableColumns(dataTable);
                this.setViewportView(dataTable);
                dataTable.setBorder(null);
                this.setBorder(null);
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                //取完数据，将当前的ResultSet对象关闭
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 表单根据表头宽度自适应列宽度
    private void fitTableColumns(JTable table) {
        JTableHeader header = table.getTableHeader();
        int rowCount = table.getRowCount();

        Enumeration columns = table.getColumnModel().getColumns();
        while (columns.hasMoreElements()) {
            TableColumn column = (TableColumn) columns.nextElement();
            int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
            int width = (int) table.getTableHeader().getDefaultRenderer()
                    .getTableCellRendererComponent(table, column.getIdentifier()
                            , false, false, -1, col).getPreferredSize().getWidth() + 30;
            header.setResizingColumn(column); // 此行很重要
            column.setWidth(width + table.getIntercellSpacing().width);
        }
    }
}
